﻿using Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace ProjectManage.Common
{
    public class AuthFilter : AuthorizeAttribute
    {
        public override void OnAuthorization(HttpActionContext context)
        {
            var authHeader = context.Request.Headers.FirstOrDefault(a => a.Key == "token");//获取接收的Token
            if (context.Request.Headers == null || !context.Request.Headers.Any() || authHeader.Key == null || string.IsNullOrEmpty(authHeader.Value.FirstOrDefault()))
            {
                Throw401Exception(context, "没有token");
                return;
            }
            var sendToken = authHeader.Value.FirstOrDefault();
            var dictPayload = DecodeToken(sendToken);
            if (dictPayload == null)
            {
                Throw401Exception(context, "token错误");
            }
            ClientUserData clientUserData = new ClientUserData()
            {
                UserNo = dictPayload["UserNo"],
                UserName = dictPayload["UserName"],
                UserDept = dictPayload["UserDept"],
                UserRole = dictPayload["UserRole"],
                UserView = dictPayload["UserView"],
            };
            if (HttpContext.Current != null)
            {
                HttpContext.Current.User = new UserPrincipal(clientUserData);
            }

        }
        private static void Throw401Exception(HttpActionContext actionContext, string exceptionString)
        {
            var response = HttpContext.Current.Response;
            throw new HttpResponseException(actionContext.Request.CreateErrorResponse(System.Net.HttpStatusCode.Unauthorized, exceptionString ?? "Unauthorized"));
        }
        private static IDictionary<string, dynamic> DecodeToken(string token)
        {
            try
            {
                string dictPayloadStr = JwtTools.ValidateJWT(token);
                if (dictPayloadStr == "签名异常")
                {
                    return null;
                }
                Dictionary<string, dynamic> dictPayload = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(dictPayloadStr);
                return dictPayload;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
}